<template>
  <div class="app-container home">
    <template v-if="isStudent">
      <template v-if="paperList.length > 0">
        <el-row :gutter="20">
          <el-col
            :md="6"
            :sm="12"
            :xs="24"
            style="margin-bottom: 12px"
            v-for="item in paperList"
            :key="item.id"
          >
            <el-card
              class="home-count-item home-test-item"
              shadow="hover"
              @click="goToTest(item)"
            >
              <div class="home-count-ico paper-bg"></div>
              <div>
                <p class="home-count-title">{{ item.paperName }}</p>
                <p class="home-count-content home-test-duration">
                  考试时长
                  <span style="margin-left: 10px">{{ item.duration }}</span
                  >分钟
                </p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </template>
      <template v-else><el-empty description="暂无考试" /></template>
    </template>
    <template v-else>
      <el-row :gutter="20">
        <el-col :md="24" :sm="24" :xs="24" style="margin-bottom: 12px">
          <el-card class="home-welcome-wrapper">
            <div class="home-welcom-left">
              <div class="home-user-avatr"></div>
              <div class="home-welcom-title">
                <span style="margin-right: 16px">你好</span>
                欢迎登录试题管理系统~
              </div>
            </div>
            <div class="home-welcom-right">
              <div class="home-welcom-right-item">
                <div class="home-welcom-right-title">班级数</div>
                <div class="home-welcom-right-content">
                  <CountTo
                    :startVal="0"
                    :endVal="indexCount.classTotal || 123"
                    :duration="1500"
                  />
                </div>
              </div>
              <div class="home-welcom-right-item">
                <div class="home-welcom-right-title">学生数</div>
                <div class="home-welcom-right-content">
                  <CountTo
                    :startVal="0"
                    :endVal="indexCount.studentTotal || 888"
                    :duration="1500"
                  />
                </div>
              </div>
              <div class="home-welcom-right-item">
                <div class="home-welcom-right-title">题目数</div>
                <div class="home-welcom-right-content">
                  <CountTo
                    :startVal="0"
                    :endVal="indexCount.questionTotal || 376"
                    :duration="1500"
                  />
                </div>
              </div>
              <div class="home-welcom-right-item">
                <div class="home-welcom-right-title">试卷数</div>
                <div class="home-welcom-right-content">
                  <CountTo
                    :startVal="0"
                    :endVal="indexCount.examination || 376"
                    :duration="1500"
                  />
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :md="16" :sm="24" :xs="24">
          <el-card shadow="hover">
            <template #header>
              <span>试卷完成率统计</span>
            </template>
            <el-row :gutter="10">
              <el-col
                :md="8"
                :sm="12"
                :xs="24"
                style="margin-bottom: 12px"
                v-for="item in finishList"
                :key="item.process"
              >
                <el-card class="home-count-item" shadow="hover">
                  <div class="home-count-ico paper-bg"></div>
                  <div>
                    <p class="home-count-title">{{ item.paperName }}</p>
                    <p class="home-count-content">
                      <el-progress
                        :width="70"
                        type="circle"
                        :percentage="item.process"
                        :color="customColors"
                      />
                    </p>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-card>
          <el-card shadow="hover" style="margin-top: 16px">
            <el-row :gutter="10">
              <el-col :md="12" :sm="24" :xs="24" style="margin-bottom: 12px">
                <template v-if="avageOption.title">
                  <EchartsCom
                    :myOption="avageOption"
                    :myStyle="{ width: '100%', height: '380px' }"
                  ></EchartsCom>
                </template>
              </el-col>
              <el-col :md="12" :sm="24" :xs="24" style="margin-bottom: 12px">
                <template v-if="subjectPieOption.title">
                  <EchartsCom
                    :myOption="subjectPieOption"
                    :myStyle="{ width: '100%', height: '380px' }"
                  ></EchartsCom
                ></template>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <el-col :md="8" :sm="24" :xs="24">
          <el-card shadow="hover">
            <template #header>
              <span>快捷入口</span>
            </template>
            <el-row :gutter="10">
              <el-col
                :md="8"
                :sm="8"
                :xs="8"
                style="margin-bottom: 12px"
                v-for="item in quicklyEnterData"
                :key="item.id"
                class="quick-access-item"
              >
                <el-icon :size="18" :color="item.color">
                  <component :is="item.icon"></component>
                </el-icon>
                <span
                  style="margin-left: 14px; cursor: pointer"
                  @click="enterRoute(item)"
                  >{{ item.label }}</span
                >
              </el-col>
            </el-row>
          </el-card>
          <el-card shadow="hover" style="margin-top: 16px">
            <template #header>
              <span>消息通知</span>
            </template>
            <el-row :gutter="10">
              <el-col
                :md="24"
                :sm="24"
                :xs="24"
                style="margin-bottom: 12px"
                v-for="item in notifyMessage"
                :key="item.id"
                class="notify-message-item"
              >
                <div class="notify-message-left"></div>
                <div class="notify-message-right">
                  <div class="message-right-top">
                    <span>通知：</span>
                    <span>{{ item.label }}</span>
                  </div>
                  <div class="message-right-bottom">{{ item.time }}</div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row></template
    >
  </div>
</template>

<script setup name="Class">
import { getSchoolClassList } from "@/api/core/class";
import { listUser } from "@/api/system/user";
import { getQuestionList } from "@/api/core/question";
import { getTestPaperList } from "@/api/core/testPaper";
import {
  getStuAnswerList,
  getHomeSubject,
  getHomeAverage,
  getHomeFinish,
  getHomeMessage,
} from "@/api/core/test";
import EchartsCom from "@/components/EchartsCom";
import * as echarts from "echarts";
import {
  getCurrentInstance,
  reactive,
  ref,
  toRefs,
  watch,
  computed,
} from "vue";
import { parseTime } from "@/utils/ruoyi";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();

const userStore = useUserStore();

const isStudent = computed(() => useUserStore().isStudent);

const router = useRouter();
const subjectPieOption = ref({});
const avageOption = ref({});
const finishList = ref([]);
const notifyMessage = ref([]);
const data = reactive({
  indexCount: {
    classTotal: 0,
    studentTotal: 0,
    questionTotal: 0,
    examination: 0,
  },
  customColors: [
    { color: "#f56c6c", percentage: 20 },
    { color: "#e6a23c", percentage: 40 },
    { color: "#5cb87a", percentage: 60 },
    { color: "#1989fa", percentage: 80 },
    { color: "#6f7ad3", percentage: 100 },
  ],

  quicklyEnterData: [
    {
      id: 1,
      label: "学生管理",
      icon: "Avatar",
      color: "",
      url: "/student/studentList",
    },
    {
      id: 2,
      label: "班级管理",
      icon: "Histogram",
      color: "#FFA876",
      url: "/grade/class",
    },
    {
      id: 3,
      label: "题库管理",
      icon: "Memo",
      color: "#86E3CE",
      url: "/question/questionList",
    },
    {
      id: 4,
      label: "试卷管理",
      icon: "Management",
      color: "#4675C0",
      url: "/examination/examinationList",
    },
    {
      id: 5,
      label: "批改管理",
      icon: "Stamp",
      color: "#FA897B",
      url: "/test/checkList",
    },
  ],
  paperList: [],
});
const { indexCount, customColors, quicklyEnterData, paperList } = toRefs(data);

/** 查询首页数据 */
function getIndexCount() {
  getSchoolClassList({}).then((res) => {
    indexCount.value.classTotal = res.total;
  });
  listUser({ roleId: 2 }).then((res) => {
    indexCount.value.studentTotal = res.total;
  });
  getQuestionList({}).then((res) => {
    indexCount.value.questionTotal = res.total;
  });
  getTestPaperList({}).then((res) => {
    indexCount.value.examination = res.total;
  });
  getHomeSubject().then((res) => {
    if (res.code == 200) {
      let totalCount = res.rows.reduce((prev, cur, index, arr) => {
        return prev + cur.part;
      }, 0);
      subjectPieOption.value = {
        title: {
          text: "按学科分类",
          top: "bottom",
          left: "center",
          textStyle: {
            color: "#333333", //字体颜色
            fontSize: 20, //文字大小
          },
        }, //标题
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
          /*formatter:function(val){   //让series 中的文字进行换行
                 console.log(val);//查看val属性，可根据里边属性自定义内容
                 var content = var['name'];
                 return content;//返回可以含有html中标签
             },*/ //自定义鼠标悬浮交互信息提示，鼠标放在饼状图上时触发事件
        }, //提示框，鼠标悬浮交互时的信息提示
        legend: {
          show: false,
          orient: "vertical",
          x: "left",
          data: ["50%-学生", "25%-老师", "25%-家长"],
        }, //图例属性，以饼状图为例，用来说明饼状图每个扇区，data与下边series中data相匹配
        graphic: {
          type: "text",
          left: "center",
          top: "center",
          style: {
            text: "题库统计\n" + "100", //使用“+”可以使每行文字居中
            textAlign: "center",
            font: "italic bolder 16px cursive",
            fill: "#000",
            width: 30,
            height: 30,
          },
        }, //此例饼状图为圆环中心文字显示属性，这是一个原生图形元素组件，功能很多
        series: [
          {
            name: "题库统计", //tooltip提示框中显示内容
            type: "pie", //图形类型，如饼状图，柱状图等
            radius: ["45%", "75%"], //饼图的半径，数组的第一项是内半径，第二项是外半径。支持百分比，本例设置成环形图。具体可以看文档或改变其值试一试
            //roseType:'area',是否显示成南丁格尔图，默认false
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  textStyle: { color: "#3c4858", fontSize: "18" },
                  formatter: function (val) {
                    //让series 中的文字进行换行
                    return val.name.split("-").join("\n");
                  },
                }, //饼图图形上的文本标签，可用于说明图形的一些数据信息，比如值，名称等。可以与itemStyle属性同级，具体看文档
                labelLine: {
                  show: true,
                  lineStyle: { color: "#3c4858" },
                }, //线条颜色
              }, //基本样式
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)", //鼠标放在区域边框颜色
                textColor: "#000",
              }, //鼠标放在各个区域的样式
            },
            data: res.rows.map((ele) => {
              return {
                value: ele.part,
                name: `${((ele.part / totalCount) * 100).toFixed(0)}%-${
                  ele.subject
                }`,
              };
            }), //数据，数据中其他属性，查阅文档
            color: ["#51CEC6", "#FFB703", "#5FA0FA"], //各个区域颜色
          }, //数组中一个{}元素，一个图，以此可以做出环形图
        ], //系列列表
      };
      console.log(subjectPieOption.value);
    }
  });
  getHomeAverage().then((res) => {
    if (res.code == 200 && res.data) {
      avageOption.value = {
        grid: {
          top: "8%", // 上边距
          left: "5%", // 左边距
          right: "8%", // 右边距
          bottom: "5%", // 下边距
        },
        title: {
          //设置图表的标题
          text: `${res.data.examPaperName}试卷平均分统计`,
          x: "center", //设置标题位置居中
          textStyle: {
            //设置主标题的文字风格
            color: "#333333", //字体颜色
            fontSize: 20, //文字大小
          },
        },

        tooltip: {
          //触发类型
          trigger: "item", //item默认为图形触发 还有axis坐标轴触发
        },

        xAxis: {
          type: "category",
          data: res.data.classStatisticsList.map((it) => it.className),
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: `${res.data.examPaperName}试卷`,
            type: "bar",
            data: res.data.classStatisticsList.map((it) =>
              it.averageScore.toFixed(2)
            ),
            // 渐变颜色
            itemStyle: {
              normal: {
                color: function (params) {
                  let colorList = [
                    ["#FA897B", "#FFDD94"],
                    ["#D0E6A5", "#FFDD94"],
                    ["#4675C0", "#B8BFD6"],
                    ["#86E3CE", "#CCABD8"],
                    ["#64A4D6", "#C782C2"],
                    ["#bdc2e8", "#e6dee9"],
                    ["#FFA876", "#FF5B00"],
                  ];
                  let colorItem = colorList[params.dataIndex];
                  return new echarts.graphic.LinearGradient(
                    0,
                    0,
                    0,
                    1, //y->y2
                    [
                      {
                        offset: 0,
                        color: colorItem[0],
                      },
                      {
                        offset: 1,
                        color: colorItem[1],
                      },
                    ],
                    false
                  );
                },
              },
            },
            markLine: {
              data: [{ type: "average", name: "平均分" }],
            },
          },
          // {
          //   type: "pie",
          //   radius: ["50%", "70%"],
          //   avoidLabelOverlap: false,
          //   label: {
          //     show: false,
          //     position: "center",
          //   },
          //   labelLine: {
          //     show: false,
          //   },
          //   emphasis: {
          //     label: {
          //       show: true,
          //       fontSize: "30",
          //       fontWeight: "bold",
          //     },
          //   },
          //   data: [
          //     { value: 335, name: "A" },
          //     { value: 310, name: "B" },
          //     { value: 234, name: "C" },
          //     { value: 135, name: "D" },
          //     { value: 1548, name: "E" },
          //   ],
          // },
        ],
      };
    }
  });
  getHomeFinish().then((res) => {
    console.log("11111", res);
    if (res.code == 200) {
      finishList.value = res.rows.map((item) => {
        return {
          paperName: item.paperName,
          process: (item.finished * 100).toFixed(2),
        };
      });
    }
  });
  getHomeMessage().then((res) => {
    console.log("11111", res);
    if (res.code == 200) {
      notifyMessage.value = res.data.map((item) => {
        return {
          id: item.id,
          label: `学生${item.stuName}提交了${item.examName}`,
          time: item.pulltime,
        };
      });
    }
  });
}
function enterRoute(item) {
  router.replace(item.url);
}
function getTestList() {
  getStuAnswerList({ stuId: userStore.userId }).then((res) => {
    paperList.value = res.rows;
  });
}
function goToTest(item) {
  proxy.$modal
    .confirm("是否开始考试？")
    .then(() => {
      router.push({
        path: "/test/detail",
        query: { paperId: item.id },
      });
    })
    .catch(() => {});
}
if (isStudent.value) {
  getTestList();
} else {
  getIndexCount();
}
</script>

<style scoped lang="scss">
.home {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  // background-image: url("../assets/images/home-bg.png");
  // background-size: cover;
  .home-welcome-wrapper {
    :deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .home-welcom-left {
        display: flex;
        align-items: center;
        font-family: PingFangSC;
        color: #333;
        font-weight: 500;
        font-size: 20px;
        font-style: normal;
        .home-user-avatr {
          width: 100px;
          height: 100px;
          background-size: 100% 100%;
          background-image: url("../assets/images/avatar.jpg");
          border-radius: 50%;
        }
        .home-welcom-title {
          margin-left: 16px;
        }
      }
      .home-welcom-right {
        display: flex;
        .home-welcom-right-item {
          position: relative;
          padding: 0 12px;
          color: #333333;
          &::before {
            content: "";
            position: absolute;
            width: 2px;
            height: 50%;
            top: 50%;
            transform: translateY(-50%);
            left: 0;
            background: #1486f6;
          }
          &:first-child::before {
            display: none;
          }
          .home-welcom-right-title {
            font-family: PingFangSC;
            color: #333;
            font-weight: 500;
            font-size: 16px;
            font-style: normal;
            margin-bottom: 10px;
          }
          .home-welcom-right-content {
            font-family: PingFangSC;
            color: #333;
            font-weight: 500;
            font-size: 18px;
            font-style: normal;
            text-align: center;
          }
        }
      }
    }
  }

  .home-count-item {
    :deep(.el-card__body) {
      display: flex;
      align-items: center;
      justify-content: space-between;
      // background-color: #f0f8ff;
      .home-count-ico {
        width: 40px;
        height: 40px;
        background-size: 100% 100%;
      }
      .paper-bg {
        background-image: url("../assets/images/paper-bg.png");
      }
      .home-count-title {
        font-family: PingFangSC;
        color: #333;
        font-weight: 500;
        font-size: 16px;
        font-style: normal;
        margin: 0;
        margin-bottom: 16px;
      }
      .home-count-content {
        font-family: PingFangSC;
        font-style: normal;
        text-align: center;
        margin: 0;

        :deep(.el-progress-circle__track) {
          stroke: #008c8c;
        }
      }
    }
    :deep(.el-card__header) {
      padding: 14px 30px;
      border-bottom: 1px solid #e7e7e7;
      display: flex;
      justify-content: space-between;
      align-items: center;
      span {
        position: relative;
        padding-left: 12px;
        font-size: 28px;
        color: #333333;
        line-height: 20px;
        &::before {
          content: "";
          position: absolute;
          width: 4px;
          height: 98%;
          top: 50%;
          transform: translateY(-50%);
          left: 0;
          background: #1486f6;
        }
      }
    }
  }
  .home-test-item {
    cursor: pointer;
    :deep(.el-card__body) {
      background-color: #f0f8ff;
      .home-test-duration {
        font-size: 12px;
        color: #c0c0c0;
      }
    }
  }
  .quick-access-item {
    display: flex;
    align-items: center;
  }
  .notify-message-item {
    display: flex;
    align-items: center;
    margin-bottom: 14px;
    font-size: 16px;
    &:last-child {
      margin-bottom: 0;
    }
    .notify-message-left {
      width: 40px;
      height: 40px;
      background-size: 100% 100%;
      background-image: url("../assets/images/avatar.jpg");
      border-radius: 50%;
    }
    .notify-message-right {
      margin-left: 16px;
      .message-right-top {
        margin-bottom: 10px;
        span {
          &:first-child {
            color: #1486f6;
          }
        }
      }
      .message-right-bottom {
        font-size: 12px;
        color: #c0c0c0;
      }
    }
  }
  .count-info {
    width: 100%;
    padding: 15px 0;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    // border: 1px #ccc solid;

    .count-info-item {
      width: 300px;
      height: 100px;
      top: 124px;
      left: 376px;

      .count-info-number {
        font-family: PingFangSC;
        color: #ffffff;
        font-weight: 500;
        font-size: 40px;
        line-height: 26px;
        font-style: normal;
        text-decoration: none;
        text-align: left;
        padding-left: 25px;
        padding-top: 20px;
      }

      .count-info-label {
        font-family: PingFangSC;
        color: #ffffff;
        font-weight: 500;
        font-size: 20px;
        line-height: 26px;
        font-style: normal;
        text-decoration: none;
        text-align: left;
        padding-left: 25px;
        padding-top: 15px;
      }
    }

    .device-count {
      background-image: url("../../src/assets/images/device.png");
      background-repeat: no-repeat;
      background-position-x: 145px;
      background-position-y: 0;
      display: block;
      cursor: pointer;
      border-radius: 20px 20px 20px 20px;
      background-color: #476af7;
      box-shadow: 0 15px 30px 0 rgba(30, 72, 220, 0.2);
    }

    .online-count {
      background-image: url("../../src/assets/images/online.png");
      background-repeat: no-repeat;
      background-position-x: 115px;
      background-position-y: 0;
      display: block;
      cursor: pointer;
      border-radius: 20px 20px 20px 20px;
      background-color: #476af7;
      box-shadow: 0 15px 30px 0 rgba(30, 72, 220, 0.2);
    }

    .alarm-count {
      background-image: url("../../src/assets/images/alarm.png");
      background-repeat: no-repeat;
      background-position-x: -20px;
      background-position-y: -85px;
      display: block;
      cursor: pointer;
      border-radius: 20px 20px 20px 20px;
      background-color: #476af7;
      box-shadow: 0 15px 30px 0 rgba(30, 72, 220, 0.2);
    }

    .rtc-count {
      background-image: url("../../src/assets/images/rtc.png");
      background-repeat: no-repeat;
      background-position-x: 165px;
      background-position-y: 3px;
      display: block;
      cursor: pointer;
      border-radius: 20px 20px 20px 20px;
      background-color: #476af7;
      box-shadow: 0 15px 30px 0 rgba(30, 72, 220, 0.2);
    }
  }

  .map-container {
    width: 100%;
    flex: 1;
  }
}
</style>
